package com.cmc6.common.util;

import com.cmc6.common.util.redis.MyRedisTemplate;
import com.cmc6.common.util.redis.RedisUtilBase;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/**
 * redis 工具类
 */
@Component
public class RedisUtil {

    public static RedisUtilBase utilBase;

    @Resource
    private void setUtilBase(RedisUtilBase utilBase) {
        RedisUtil.utilBase = utilBase;
    }

    /**
     * 获取 MyRedisTemplate
     */
    @Deprecated // 原因：因为集群模式，不支持切换 db，只有 db0
    public static <T> MyRedisTemplate<T> createRedisConnectionFactory(int db) {
        return utilBase.createRedisConnectionFactory(db);
    }

    /**
     * scan获取 redis所有 key，通过 模糊匹配 matchKey
     */
    public static Set<String> scan(String matchKey, int db) {

        return createRedisConnectionFactory(db).execute((RedisCallback<Set<String>>)connection -> {
            Set<String> keysTmp = new HashSet<>();
            Cursor<byte[]> cursor = connection.scan(ScanOptions.scanOptions().match("*" + matchKey + "*").build());
            while (cursor.hasNext()) {
                keysTmp.add(new String(cursor.next()));
            }
            return keysTmp;
        });
    }
}
